package com.erik.lin.collect;

import com.erik.lin.domain.DbInfo;
import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by Erik on 2018/2/7.
 */
public abstract class CollectAdapter {

    protected SqlSessionFactory sqlSessionFactory;

    public CollectAdapter(DbInfo dbInfo) {
        initializeSqlSessionFactory(dbInfo);
    }

    public abstract void initializeSqlSessionFactory(DbInfo dbInfo);

    /** mysql采集模式名称获取 */
    private void initializeMysqlProperties(DbInfo dbInfo){
        String sourUrl = dbInfo.getParam().get("url");
        String schemaName = sourUrl.substring(sourUrl.lastIndexOf("/") + 1);
        if(schemaName.indexOf("?") > 0) {
            schemaName = schemaName.substring(0, schemaName.indexOf("?"));
        }
        dbInfo.getParam().put("tableSchema", schemaName);
    }

    public Configuration getConfiguration(DbInfo dbInfo) {

        Properties properties = new Properties();
        properties.setProperty("driver", dbInfo.getParam().get("driver"));
        properties.setProperty("url", dbInfo.getParam().get("url"));
        properties.setProperty("username", dbInfo.getParam().get("username"));
        properties.setProperty("password", dbInfo.getParam().get("password"));

        PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory();
        pooledDataSourceFactory.setProperties(properties);
        DataSource dataSource = pooledDataSourceFactory.getDataSource();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        return configuration;
    }

    public List<Map<String, String>> collectTableList(DbInfo dbInfo) {
        List<Map<String, String>> tableList = null;
        SqlSession session= sqlSessionFactory.openSession();
        try {
            tableList = session.selectList("com.erik.lin.collect.selectTableList",dbInfo.getParam());
        }catch(Exception ex) {
            ex.printStackTrace();
            throw ex;
        }finally {
            session.close();
        }
        return tableList;
    }


}